﻿using jinmaMesProxy.DataAccess;
using jinmaMesProxy.Excep;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json.Serialization;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization;
using System.Text.Unicode;

namespace jinmaMesProxy
{
    public static class Booter
    {
        public static void Setup(WebApplicationBuilder builder)
        {
            RuntimeVariable.GLOBAL_CONFIG = builder.Configuration;
            RuntimeVariable.ROOT_PATH = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            RuntimeVariable.OptUser = ConfigReader.ReadSetting("Sys", "ErpUser");
            RuntimeVariable.ACCID = ConfigReader.ReadSetting("Sys", "AccId");

            builder.Services.AddScoped<ErpDbInstance>();
            builder.Services.AddHttpContextAccessor();
            builder.Services.AddScoped<ErpDbInstance>();
            builder.Services.AddControllers(o =>
            {
                o.Filters.Add(typeof(GlobalExceptions));
                o.Filters.Add(typeof(NaviteExceptions));
                o.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true;
            }).AddJsonOptions(o =>
            {
                o.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                o.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
            });
            builder.Services.AddMvc(o =>
            {
                o.ValueProviderFactories.Add(new JQueryQueryStringValueProviderFactory());
            }).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            builder.Services.AddAuthorization();
            builder.Services.AddScoped<IAuthorizationHandler, MyAuthorizationHandler>();
        }
    }
}
